﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LightingReflectionApp
{
    public partial class IlluminationForm : Form
    {
        private IlluminationCalculator calculator;
        private Surface surface;
        private Label infoLabel;
        private PictureBox pictureBox;
        private PictureBox pictureBoxOX;
        private PictureBox pictureBoxOY;
        private double scale;

        public IlluminationForm(IlluminationCalculator calculator, string info)
        {
            this.calculator = calculator;
            this.surface = calculator.Surface;
           
            InitializeComponent();
            AddComponent();
            //calculator.CalculateIlluminationFromLamps();
            CalculateScale();
            this.Text = "Диаграмма освещенности. " + info;
        }

        private void AddComponent()
        {
            this.Size = new Size(870, 630);
            this.Resize += new EventHandler(OnResize);

            pictureBoxOX = new PictureBox
            {
                Location = new Point(60, 10),
                Size = new Size(810, 30),
                BackColor = Color.Transparent
            };
            pictureBoxOX.Paint += new PaintEventHandler(DrawOXScale);

            pictureBoxOY = new PictureBox
            {
                Location = new Point(10, 40),
                Size = new Size(50, 500),
                BackColor = Color.Transparent
            };
            pictureBoxOY.Paint += new PaintEventHandler(DrawOYScale);

            pictureBox = new PictureBox
            {
                Location = new Point(60, 40),
                Size = new Size(750, 500),
                BackColor = Color.Transparent
            };
            pictureBox.Paint += new PaintEventHandler(DrawIllumination);

            infoLabel = new Label
            {
                Location = new Point(10, 560),
                Size = new Size(850, 30),
                Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right
            };

            this.Controls.Add(pictureBoxOX);
            this.Controls.Add(pictureBoxOY);
            this.Controls.Add(pictureBox);
            this.Controls.Add(infoLabel);

            pictureBox.MouseMove += new MouseEventHandler(OnMouseMove);
        }

        private void CalculateScale()
        {
            double pL = pictureBox.Width;
            double pW = pictureBox.Height;
            double L = surface.Room.Length;
            double W = surface.Room.Width;

            if (L * W != 0)         //не делим на 0
                scale = Math.Min(pL / L, pW / W);
            else
                scale = 1;
        }

        private void DrawIllumination(object sender, PaintEventArgs e)
        {
            Graphics g = e.Graphics;
            int squaresPerRow = surface.Squares.GetLength(1);
            int squaresPerColumn = surface.Squares.GetLength(0);

            // Находим максимальное значение освещенности
            double maxIllumination = 0;
            for (int i = 0; i < squaresPerRow; i++)
            {
                for (int j = 0; j < squaresPerColumn; j++)
                {
                    if (surface.Squares[j, i].Illumination > maxIllumination)
                    {
                        maxIllumination = surface.Squares[j, i].Illumination;
                    }
                }
            }

            //Комфортная освещенность от 100 до 500
            maxIllumination = Math.Max(maxIllumination, 100);    //Если везде очень темно, ставим 100 - минимум
            maxIllumination = Math.Min(maxIllumination, 500);    //Если везде очень светло, ставим 500 - максимум

            for (int i = 0; i < squaresPerRow; i++)
            {
                for (int j = 0; j < squaresPerColumn; j++)
                {
                    double illumination = surface.Squares[j, i].Illumination;

                    int colorIntensity = (int)(illumination / maxIllumination * 255);
                    colorIntensity = Math.Min(colorIntensity, 255); // Ограничиваем максимальное значение 255

                    Color color = Color.FromArgb(colorIntensity, colorIntensity, colorIntensity);
                    Brush brush = new SolidBrush(color);

                    // Преобразуем координаты и размеры из метров в пиксели
                    double x = i * surface.SquareSide * scale;
                    double y = j * surface.SquareSide * scale;
                    double side = surface.SquareSide * scale;

                    g.FillRectangle(brush, (float)x, (float)y, (float)side, (float)side);
                }
            }
        }

        private void OnMouseMove(object sender, MouseEventArgs e)
        {
            double x = e.X / scale;
            double y = e.Y / scale;

            int squareX = (int)(x / surface.SquareSide);
            int squareY = (int)(y / surface.SquareSide);

            if (squareX >= 0 && squareX < surface.Squares.GetLength(1) && squareY >= 0 && squareY < surface.Squares.GetLength(0))
            {
                double illumination = surface.Squares[squareY, squareX].Illumination;
                infoLabel.Text = $"Координата X: {x:F2} м, Координата Y: {y:F2} м, Освещенность: {illumination:F2} лк";
            }
        }

        private void DrawOXScale(object sender, PaintEventArgs e)
        {
            Graphics g = e.Graphics;
            double L = surface.Room.Length;

            for (int i = 0; i <= L; i++)
            {
                double x = i * scale;
                g.DrawLine(Pens.Black, (float)x, 20, (float)x, 30);
                g.DrawString(i.ToString(), DefaultFont, Brushes.Black, (float)x, 0);
            }
        }

        private void DrawOYScale(object sender, PaintEventArgs e)
        {
            Graphics g = e.Graphics;
            double W = surface.Room.Width;

            for (int i = 0; i <= W; i++)
            {
                double y = i * scale;
                g.DrawLine(Pens.Black, 40, (float)y, 50, (float)y);
                g.DrawString(i.ToString(), DefaultFont, Brushes.Black, 0, (float)y);
            }
        }

        private void OnResize(object sender, EventArgs e)
        {
            // Обновляем размеры и позиции элементов при изменении размеров формы
            int formWidth = this.ClientSize.Width;
            int formHeight = this.ClientSize.Height;

            pictureBoxOX.Size = new Size(formWidth - 70, 30);
            pictureBoxOY.Size = new Size(50, formHeight - 80);
            pictureBox.Size = new Size(formWidth - 70, formHeight - 80);
            infoLabel.Location = new Point(10, formHeight - 30);
            infoLabel.Size = new Size(formWidth - 20, 30);

            CalculateScale();

            // Перерисовываем элементы
            pictureBoxOX.Invalidate();
            pictureBoxOY.Invalidate();
            pictureBox.Invalidate();
        }
    }
}
